<template>
  <div>
    <el-tag v-for="(tag,index) in list"
            :key="index"
            closable
            :disable-transitions="false"
            @close="handleClose(tag)">
      {{tag}}
    </el-tag>
    <template v-if="inputVisible">
      <el-input class="input-new-tag"
                v-model="inputValue"
                ref="saveTagInput"
                size="small"
                @blur="handleInputConfirm">
      </el-input>
    </template>
    <template v-else>
      <el-button class="button-new-tag"
                 size="small"
                 @click="showInput">+ New</el-button>
    </template>
  </div>
</template>

<script>
export default {
  model: {
    prop: 'value',
    event: 'change',
  },
  props: {
    value: {
      type: Array,
      default: () => []
    }
  },
  data () {
    return {
      inputVisible: false,
      inputValue: ""
    }
  },
  computed: {
    list: {
      get () {
        return this.value
      },
      set (v) {
        this.$emit('change', v)
      }
    }
  },
  methods: {
    handleClose (tag) {
      this.list = this.list.filter((item) => item !== tag)
    },
    showInput () {
      this.inputVisible = true
      this.$nextTick(_ => {
        this.$refs.saveTagInput.$refs.input.focus()
      })
    },
    handleInputConfirm () {
      if (this.inputValue) {
        this.list.push(this.inputValue)
      }
      this.inputVisible = false
      this.inputValue = ''
    },
  }
}
</script>

<style lang="scss" scoped>
.button-new-tag {
  margin-left: 10px;
  height: 32px;
  line-height: 30px;
  padding-top: 0;
  padding-bottom: 0;
}
.input-new-tag {
  width: 90px;
  margin-left: 10px;
  vertical-align: bottom;
}
</style>